<template>
	<view class="settlement-page">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<text class="back-icon" @click="goBack">返回</text>
			<text class="navbar-title">订单结算</text>
		</view>

		<!-- 订单详情 -->
		<view class="order-info">
			<view class="section-title">订单详情</view>
			<view class="product-list">
				<view class="product-item" v-for="(product, index) in products" :key="index">
					<image class="product-image" :src="product.good.goods.picUrl" mode="aspectFill" />
					<view class="product-details">
						<text class="product-name">{{ product.good.goods.name }}</text>
						<text class="product-quantity">数量: {{ product.quantity }}</text>
					</view>
					<text class="product-price">￥{{ product.price.toFixed(2) }}</text>
				</view>
			</view>
		</view>

		<!-- 配送地址 -->
		<view class="shipping-address">
			<view class="section-title">配送地址</view>
			<view v-if="selectedAddress" class="address-info">
				<text>收货人: {{ selectedAddress.name }}</text>
				<text>电话: {{ selectedAddress.tel }}</text>
				<text>地址: {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.county }}
					{{ selectedAddress.addressDetail }}</text>
			</view>
			<view v-else class="no-address" @click="selectAddress">
				请选择收货地址
			</view>
		</view>

		<!-- 选择支付方式 -->
		<view class="payment-method">
			<view class="section-title">支付方式</view>
			<radio-group class="radio-group" @change="changePaymentMethod">
				<label class="radio-item" v-for="(payment, index) in paymentMethods" :key="index">
					<radio :value="payment.value" :checked="payment.value === selectedPaymentMethod" />
					<text>{{ payment.label }}</text>
				</label>
			</radio-group>
		</view>

		<!-- 订单总结 -->
		<view class="order-summary">
			<view class="summary-item">
				<text>商品总价</text>
				<text>￥{{ totalAmount.toFixed(2) }}</text>
			</view>
			<view class="summary-total">
				<text>实付金额：</text>
				<text class="total-price">￥{{ totalAmount.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 合同内容展示区域 -->
		<view class="contract-section" v-if="htmlContent">
			<view class="section-title">合同预览</view>
			<view class="contract-box">
				<button class="view-contract-btn" @click="viewFullContract">查看完整合同</button>
			</view>
		</view>

		<!-- 提交订单 -->
		<view class="submit-order-btn">
			<button class="contract-btn" @click="navigateToContractPage" :disabled="!selectedAddress">生成合同</button>
			<button class="submit-btn" @click="submitOrder" :disabled="!selectedAddress || !htmlContent">提交订单</button>
		</view>

		<!-- 加载提示 -->
		<view v-if="loading" class="loading-mask">
			<view class="loading-content">
				<text>{{ loadingText }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				products: [],
				selectedAddress: null,
				paymentMethods: [{
					value: '签署合同',
					label: '签署合同'
				}],
				selectedPaymentMethod: '签署合同',
				htmlContent: "",
				supplierCompany: {},
				buyerCompany: {},
				info: {},
				loading: false,
				loadingText: '加载中...',
				orderId: 0
			};
		},
		onLoad(res) {
			if (res.data) {
				this.info = JSON.parse(decodeURIComponent(res.data));
			} else {
				this.showToast('订单数据加载失败');
				setTimeout(() => {
					this.goBack();
				}, 1500);
			}
		},
		mounted() {
			this.initPageData();
		},
		computed: {
			totalAmount() {
				return this.products.reduce((acc, product) => acc + product.price, 0);
			},
			payableAmount() {
				return this.totalAmount;
			}
		},
		methods: {
			// 初始化页面数据
			initPageData() {
				this.loading = false;
				this.loadingText = '加载订单信息...';

				this.products = this.info.cartItems || [];

				// 先获取供应商信息
				this.getSupplierCompanyInfo(this.info.userId);
			},

			// 获取供应商公司信息
			getSupplierCompanyInfo(userId) {
				if (!userId) {
					this.showToast('缺少供应商ID');
					this.loading = false;
					return;
				}

				uni.request({
					url: this.baseUrl + "/wx/companyInfo/getCompanyInfo",
					method: 'GET',
					data: {
						userId
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.errno === 0 && res.data.data) {
							this.supplierCompany = res.data.data;
							// 获取完供应商信息后，获取买家信息
							this.getBuyerCompanyInfo();
						} else {
							this.showToast('获取供应商信息失败');
							this.loading = false;
						}
					},
					fail: (error) => {
						console.error('获取供应商公司信息失败:', error);
						this.showToast('获取供应商信息失败');
						this.loading = false;
					}
				});
			},

			// 获取买家公司信息
			getBuyerCompanyInfo() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.id) {
					this.showToast('未获取到用户信息');
					this.loading = false;
					return;
				}

				uni.request({
					url: this.baseUrl + "/wx/companyInfo/getCompanyInfo",
					method: 'GET',
					data: {
						userId: userInfo.id
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.errno === 0 && res.data.data) {
							this.buyerCompany = res.data.data;
							// 所有数据加载完成
							this.loading = false;
						} else {
							this.showToast('获取买家信息失败');
							this.loading = false;
						}
					},
					fail: (error) => {
						console.error('获取买家公司信息失败:', error);
						this.showToast('获取买家信息失败');
						this.loading = false;
					}
				});
			},

			// 生成合同
			navigateToContractPage() {
				if (!this.selectedAddress) {
					this.showToast('请选择收货地址');
					return;
				}
				this.loading = true;
				this.loadingText = '正在生成合同...';
				const encodedData = {
					products: this.products,
					address: {
						name: this.selectedAddress.name,
						tel: this.selectedAddress.tel,
						province: this.selectedAddress.province,
						city: this.selectedAddress.city,
						county: this.selectedAddress.county,
						addressDetail: this.selectedAddress.addressDetail
					},
					paymentMethod: this.selectedPaymentMethod,
					totalAmount: this.totalAmount,
					payableAmount: this.totalAmount
				};

				uni.request({
					url: `${this.baseUrl}/wx/order/generateContract`,
					method: 'POST',
					data: {
						"encodedData": encodedData,
						"buyerCompany": this.buyerCompany,
						"supplierCompany": this.supplierCompany
					},
					success: (res) => {
						this.loading = false;
						console.log(res);
						if (res.data.errno === 0) {
							this.htmlContent = this.processHtmlContent(res.data.data.html);
							this.orderId = res.data.data.orderId;
							this.showToast('合同已生成', 'success');
						} else {
							this.showToast('生成合同失败');
						}
					},
					fail: (error) => {
						this.loading = false;
						this.showToast('网络错误，请重试');
					}
				});
			},
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 选择地址
			selectAddress() {
				uni.navigateTo({
					url: '/pages/setUp/subpage/CompanyAddress?select=true'
				});
			},

			// 更改支付方式
			changePaymentMethod(e) {
				this.selectedPaymentMethod = e.detail.value;
			},

			// 提交订单
			submitOrder() {
				if (!this.selectedAddress) {
					this.showToast('请选择收货地址');
					return;
				}

				if (!this.htmlContent && this.orderId!=0) {
					this.showToast('请先生成合同');
					return;
				}

				this.loading = true;
				this.loadingText = '正在提交订单...';
				// 发送订单提交请求
				uni.request({
					url: `${this.baseUrl}/wx/order/insert`,
					method: 'POST',
					data: {
						// 1. 商品信息 - 包含订单中所有商品的详细信息
						products: this.products.map((product, index) => ({
							id: product.id, // 订单商品ID
							name: product.good.goods.name, // 商品名称：显示用的商品标题
							imageUrl: product.good.goods.picUrl, // 商品图片：商品主图URL地址
							quantity: product.quantity, // 购买数量：用户选择的购买件数
							unitPrice: product.price, // 单价：商品的单件价格
							productId: product.good.goods.id, // 商品ID：商品的唯一标识符
							specifications: product.good.goods.specifications, // 规格信息：商品的规格参数
							properties: product.good.goods // 商品属性：商品的其他属性信息
						})),
						// 2. 收货地址信息 - 订单收货人和配送地址的详细信息
						delivery: {
							id: this.selectedAddress.id, // 地址ID：该地址在系统中的唯一标识
							recipient: this.selectedAddress.name, // 收货人：收件人姓名
							phone: this.selectedAddress.tel, // 联系电话：收货人手机号码
							province: this.selectedAddress.province, // 省份：收货地址所在省
							city: this.selectedAddress.city, // 城市：收货地址所在市
							district: this.selectedAddress.county, // 区县：收货地址所在区/县
							addressDetail: this.selectedAddress.addressDetail, // 详细地址：具体街道门牌号
							fullAddress: `${this.selectedAddress.province}${this.selectedAddress.city}${this.selectedAddress.county}${this.selectedAddress.addressDetail}`, // 完整地址：省市区详细地址的完整组合
						},
						// 3. 支付信息 - 订单支付相关的信息
						payment: {
							id: Date.now(), // 支付ID：支付记录的唯一标识
							method: this.selectedPaymentMethod, // 支付方式：用户选择的支付方式
							totalAmount: this.totalAmount, // 总金额：订单商品总价
							payableAmount: this.payableAmount, // 应付金额：实际需要支付的金额
							currency: 'CNY' // 货币单位：使用的货币类型（人民币）
						},
						// 4. 公司信息 - 交易双方公司的详细信息
						companies: {
							supplier: {
								id: this.supplierCompany.id, // 供应商ID
								name: this.supplierCompany.companyName, // 供应商公司名称
								address: this.supplierCompany.registeredAddress, // 供应商注册地址
								phone: this.supplierCompany.contactNumber, // 供应商联系电话
								details: this.supplierCompany // 供应商的其他详细信息
							},
							buyer: {
								id: this.buyerCompany.id, // 买家公司ID
								name: this.buyerCompany.companyName, // 买家公司名称
								address: this.buyerCompany.registeredAddress, // 买家注册地址
								phone: this.buyerCompany.contactNumber, // 买家联系电话
								details: this.buyerCompany // 买家的其他详细信息
							}
						},
						// 5. 合同信息 - 订单关联的合同信息
						contract: {
							content: this.orderId, // 合同内容：合同的HTML格式内容
							length: this.htmlContent.length // 合同长度：合同内容的字符长度
						},
						// 6. 原始订单信息 - 保存原始的完整订单数据
						originalOrder: this.info, // 原始订单数据：包含订单的所有原始信息
						// 7. 时间信息 - 订单相关的时间记录
						time: {
							createTime: new Date().toLocaleString(), // 创建时间：订单创建的本地时间字符串
							timestamp: Date.now() // 时间戳：订单创建时的毫秒级时间戳
						}
					},
					success: (res) => {
						this.loading = false;
						if (res.data.errno === 0) {
							uni.showModal({
								title: '提示',
								content: '订单提交成功！',
								showCancel: false,
								success: () => {
									uni.redirectTo({
										url: '/pages/orderSuccess/orderSuccess'
									});
								}
							});
						} else {
							this.showToast(res.data.errmsg || '订单提交失败');
						}
					},
					fail: (error) => {
						console.error('提交订单失败:', error);
						this.loading = false;
						this.showToast('网络错误，请重试');
					}
				});
			},

			// 统一的Toast提示
			showToast(title, icon = 'none') {
				uni.showToast({
					title,
					icon
				});
			},

			// 处理 HTML 内容
			processHtmlContent(html) {
				// 不添加样式标签，直接返回原始HTML
				return html;
			},

			// 查看完整合同
			viewFullContract() {
				console.log(1111);
				// 将合同内容存储到本地缓存
				uni.setStorageSync('contractHtml', this.htmlContent);
				// 跳转到合同预览页面
				uni.navigateTo({
					url: '/pages/Information/orderConfirmationPage/contractPreview'
				});
			}
		},
		onShow() {
			const selectedAddress = uni.getStorageSync('selectedAddress');
			if (selectedAddress) {
				this.selectedAddress = selectedAddress;
				uni.removeStorageSync('selectedAddress');
			}
		}
	};
</script>

<style scoped>
	.settlement-page {
		font-family: 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
		background-color: #f5f7fa;
		padding: 15px;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.navbar,
	.order-info,
	.shipping-address,
	.payment-method,
	.contract-preview,
	.order-summary,
	.submit-order-btn {
		width: 95%;
		max-width: 1500px;
		background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
		padding: 15px;
		margin: 5px 0;
		border-radius: 20px;
		box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.navbar:hover,
	.order-info:hover,
	.shipping-address:hover,
	.payment-method:hover,
	.contract-preview:hover,
	.order-summary:hover,
	.submit-order-btn:hover {
		box-shadow: 0px 6px 25px rgba(0, 0, 0, 0.15);
		transform: translateY(-4px);
	}

	.navbar-title {
		font-size: 1.2em;
		font-weight: 700;
		color: #333;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin-bottom: 15px;
		padding-bottom: 8px;
		border-bottom: 1px solid #eee;
	}

	.product-list {
		display: flex;
		flex-direction: column;
	}

	.product-item {
		display: flex;
		align-items: flex-start;
		padding: 8px;
		border-bottom: 1px solid #eaeaea;
		transition: all 0.3s ease;
	}

	.product-item:hover {
		background: rgba(255, 255, 255, 0.1);
		transform: scale(1.02);
	}

	.product-image {
		width: 100px;
		height: 100px;
		margin-right: 15px;
		border-radius: 10px;
		box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.product-image:hover {
		box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
	}

	.product-details {
		flex: 1;
	}

	.product-name {
		font-weight: 600;
		color: #34495e;
		margin-bottom: 5px;
		text-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
	}

	.product-quantity {
		color: #7f8c8d;
		font-size: 0.9em;
	}

	.product-price {
		font-weight: bold;
		color: #e74c3c;
		margin-left: auto;
		font-size: 1.1em;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
	}

	.no-address {
		padding: 15px;
		text-align: center;
		color: #3498db;
		background: #f0f9ff;
		border-radius: 10px;
		margin-bottom: 20px;
		border: 1px dashed #3498db;
		box-shadow: 0px 2px 6px rgba(52, 152, 219, 0.1);
		transition: all 0.3s ease;
		cursor: pointer;
	}

	.no-address:hover {
		background: #e1f0fa;
		box-shadow: 0px 4px 12px rgba(52, 152, 219, 0.2);
	}

	.address-info {
		background-color: #f8f8f8;
		padding: 10px;
		border-radius: 4px;
		margin-bottom: 8px;
		transition: all 0.3s ease;
	}

	.address-info:hover {
		box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
	}

	.address-info text {
		display: block;
		margin-bottom: 5px;
		color: #333;
	}

	/* 按钮容器样式 */
	.submit-order-btn {
		text-align: center;
		margin-top: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 12px;
		padding: 15px;
	}

	/* 基础按钮样式 */
	.submit-btn,
	.contract-btn {
		width: 100%;
		max-width: 400px;
		height: 50px;
		border: none;
		border-radius: 25px;
		font-size: 18px;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0.9;
		letter-spacing: 2px;
	}

	/* 生成合同按钮 */
	.contract-btn {
		background: #2ecc71;
		color: #ffffff;
		font-size: 16px;
		font-weight: 500;
		text-shadow: none;
		box-shadow: 0 4px 10px rgba(46, 204, 113, 0.3);
	}

	.contract-btn:hover {
		opacity: 1;
		background: #27ae60;
		transform: translateY(-2px);
	}

	/* 提交订单按钮 */
	.submit-btn {
		background: #8e44ad;
		color: #ffffff;
		font-size: 16px;
		font-weight: 500;
		text-shadow: none;
		box-shadow: 0 4px 10px rgba(142, 68, 173, 0.3);
	}

	.submit-btn:hover {
		opacity: 1;
		background: #6c3483;
		transform: translateY(-2px);
	}

	/* 禁用状态 */
	.submit-btn:disabled,
	.contract-btn:disabled {
		background: #95a5a6;
		color: #ffffff;
		opacity: 0.8;
		cursor: not-allowed;
		box-shadow: none;
		transform: none;
	}

	.radio-group {
		display: flex;
		flex-direction: row;
		margin-top: 15px;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-right: 20px;
		cursor: pointer;
		transition: color 0.3s ease;
	}

	.radio-item:hover {
		color: #3498db;
	}

	.radio-item radio {
		margin-right: 5px;
	}

	.order-summary {
		width: 90%;
		max-width: 1200px;
		background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
		padding: 30px;
		margin: 10px 0;
		border-radius: 20px;
		box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.order-summary:hover {
		box-shadow: 0px 6px 25px rgba(0, 0, 0, 0.15);
		transform: translateY(-4px);
	}

	.summary-item,
	.summary-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.summary-item {
		margin-bottom: 15px;
		font-size: 1.1em;
		color: #34495e;
	}

	.summary-total {
		font-size: 1.3em;
		font-weight: 600;
		color: #2c3e50;
		margin-top: 15px;
		border-top: 2px solid #e0e0e0;
		padding-top: 10px;
	}

	.total-price {
		color: #e74c3c;
		font-weight: bold;
	}

	.main-content {
		width: 95%;
		max-width: 1500px;
		margin: 0 auto;
	}

	.contract-preview {
		background: #ffffff;
		border-radius: 20px;
		padding: 15px;
		margin: 10px 0;
		box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
	}

	.contract-wrapper {
		width: 100%;
		background: #f8f9fa;
		border: 1px solid #e9ecef;
		border-radius: 8px;
		padding: 15px;
		box-sizing: border-box;
	}

	.contract-content {
		max-height: 400px;
		overflow-y: auto;
		width: 100%;
		box-sizing: border-box;
		overflow-x: hidden;
	}

	/* 强制所有HTML元素适应容器宽度 */
	.contract-content :deep(*) {
		max-width: 100% !important;
		box-sizing: border-box !important;
		word-break: break-word !important;
	}

	/* 表格样式 */
	.contract-content :deep(table) {
		width: 100% !important;
		border-collapse: collapse;
		table-layout: fixed !important;
		margin: 8px 0;
	}

	.contract-content :deep(td),
	.contract-content :deep(th) {
		border: 1px solid #dee2e6;
		padding: 8px;
		font-size: 14px;
		text-align: left;
		word-break: break-all;
		max-width: 100% !important;
		overflow: hidden;
	}

	/* 图片样式 */
	.contract-content :deep(img) {
		max-width: 100% !important;
		height: auto !important;
	}

	/* 强制段落和标题适应容器 */
	.contract-content :deep(p),
	.contract-content :deep(h1),
	.contract-content :deep(h2),
	.contract-content :deep(h3),
	.contract-content :deep(h4),
	.contract-content :deep(div) {
		width: 100% !important;
		max-width: 100% !important;
		word-wrap: break-word !important;
	}

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.loading-content {
		background: #ffffff;
		padding: 15px 30px;
		border-radius: 10px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	/* 添加全局样式控制 */
	page {
		overflow-x: hidden;
	}

	.contract-section {
		width: 95%;
		max-width: 1500px;
		background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
		padding: 15px;
		margin: 5px 0;
		border-radius: 20px;
		box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.contract-section:hover {
		box-shadow: 0px 6px 25px rgba(0, 0, 0, 0.15);
		transform: translateY(-4px);
	}

	.contract-box {
		display: flex;
		justify-content: center;
		padding: 20px;
	}

	.view-contract-btn {
		background: #3498db;
		color: white;
		padding: 10px 20px;
		border-radius: 8px;
		border: none;
		font-size: 16px;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.view-contract-btn:hover {
		background: #2980b9;
		transform: translateY(-2px);
	}
</style>